﻿Option Strict Off
Option Explicit On
Imports Microsoft.VisualBasic.PowerPacks.Printing.Compatibility.VB6
Imports System.Data.SqlClient
Public Class frmModuloDiesel
    Private m_ScannerManager As UFScannerManager
    Private m_Scanner As UFScanner
    Private m_Matcher As UFMatcher
    Private m_Database As UFDatabase
    Private m_strError As String
    Private m_Serial As Integer
    Private m_UserID As String
    Private m_FingerIndex As Integer
    Private m_Template1 As Byte()
    Private m_Template1Size As Integer
    Private m_Template2 As Byte()
    Private m_Template2Size As Integer
    Private m_Memo As String
    '
    Private Const MAX_USERID_SIZE As Integer = 50
    Private Const MAX_TEMPLATE_SIZE As Integer = 1024
    Private Const MAX_MEMO_SIZE As Integer = 100
    '
    Private Const DATABASE_COL_SERIAL As Integer = 0
    Private Const DATABASE_COL_USERID As Integer = 1
    Private Const DATABASE_COL_FINGERINDEX As Integer = 2
    Private Const DATABASE_COL_TEMPLATE1 As Integer = 3
    Private Const DATABASE_COL_TEMPLATE2 As Integer = 4
    Private Const DATABASE_COL_MEMO As Integer = 5

    Dim Bitacora As New clsActividad
    Dim Usuario As New clsUsuarioPrincipal
    Dim Diesel As New clsDiesel
    Dim Temp As New clsDieselTemp
    Dim DieselSinRecorrido As New clsDieselSinRecorrido
    Private mstrCondicion As String

    Public WriteOnly Property Condicion() As String
        Set(ByVal value As String)
            mstrCondicion = value
        End Set
    End Property

    Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click
        Close()

    End Sub

    Private Sub frmModuloDiesel_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        Bitacora.RegistraActividad("Cerró el Módulo de Diesel")
        Usuario.Ubicacion("Ventana Principal")
    End Sub

    Private Sub frmModuloDiesel_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ToolStrip1.Cursor = Cursors.Hand
        ToolStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.System


        CargaTanques()
        CargaBuses()
        CargaRutas()


        Bitacora.RegistraActividad("Ingresó al Módulo de Diesel")
        Usuario.Ubicacion("Módulo de Diesel")

        txtFolio.Text = (BuscarIntDatoCitra("Select MAX(IdDiesel) as Id from Diesel")) + 1
        txtFolio.Text = 0
        datFecha.Enabled = False
        txtAutobus.Focus()
        lblDiferencia.Text = ""


        m_ScannerManager = New UFScannerManager(Me)
        m_Scanner = Nothing
        m_Matcher = Nothing
        m_Database = Nothing

        m_Template1 = New Byte(MAX_TEMPLATE_SIZE) {}
        m_Template2 = New Byte(MAX_TEMPLATE_SIZE) {}
        tbxMessage.Clear()

        Iniciar()

    End Sub
    Sub BuscarRendimiento()
        Dim RendimientoStandard As Double = BuscarDblDatoCitra("SELECT Importe02 FROM Autobuses WHERE NoEconomico='" & txtAutobus.Text.Trim & "'")
        Dim IdAutobus As Integer = BuscarIntDatoCitra("SELECT IdAutobus FROM Autobuses WHERE NoEconomico='" & txtAutobus.Text.Trim & "'")
        Dim UltimoRendimiento As Double = BuscarIntDatoCitra("SELECT RendimientoDia FROM Diesel Where IdAutobus=" & IdAutobus & " ORDER BY IdDiesel DESC")
        txtRendimientoStandar.Text = Format(RendimientoStandard, "###,###.#0")
        txtRendimientoAnterior.Text = Format(UltimoRendimiento, "###,###.#0")
    End Sub
    Sub Iniciar()
        '==========================================================================='
        ' Initilize scanners
        '==========================================================================='
        Dim ufs_res As UFS_STATUS
        Dim nScannerNumber As Integer

        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        ufs_res = m_ScannerManager.Init()
        Windows.Forms.Cursor.Current = Me.Cursor
        If (ufs_res = UFS_STATUS.OK) Then
            tbxMessage.AppendText("Conexión del scanner: Correcta" & vbNewLine)
        Else
            UFScanner.GetErrorString(ufs_res, m_strError)
            tbxMessage.AppendText("Conexión del scanner: " & m_strError & vbNewLine)
            Exit Sub
        End If

        nScannerNumber = m_ScannerManager.Scanners.Count
        'tbxMessage.AppendText("UFScanner GetScannerNumber: " & nScannerNumber & vbNewLine)

        If (nScannerNumber = 0) Then
            tbxMessage.AppendText("No hay scanners disponibles" & vbNewLine)
            Exit Sub
        Else
            tbxMessage.AppendText("El primer scanner será usado" & vbNewLine)
        End If

        m_Scanner = m_ScannerManager.Scanners(0)
        '==========================================================================='

        '==========================================================================='
        ' Open database
        '==========================================================================='
        Dim ufd_res As UFD_STATUS

        m_Database = New UFDatabase()

        ' Generate connection string
        Dim DataSource As String
        Dim Connection As String
        '
        'DataSource = "UFDatabase.mdb"
        '
        'tbxMessage.AppendText("Select a database file" & vbNewLine)
        'Dim dlg As OpenFileDialog = New OpenFileDialog()
        'dlg.FileName = "UFDatabase.mdb"
        'dlg.Filter = "Database Files (*.mdb)|*.mdb"
        'dlg.DefaultExt = "mdb"
        'Dim res As DialogResult = dlg.ShowDialog()
        'If (res <> Windows.Forms.DialogResult.OK) Then
        'Exit Sub
        'End If

        DataSource = CitraInicial & "\UFDatabase.mdb"
        '
        Connection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DataSource & ";"

        ' Open database
        ufd_res = m_Database.Open(Connection, "", "")
        If (ufd_res = UFD_STATUS.OK) Then
            tbxMessage.AppendText("Apertura de la base de datos: Correcta" & vbNewLine)
        Else
            UFDatabase.GetErrorString(ufd_res, m_strError)
            tbxMessage.AppendText("Apertura de la base de datos: " & m_strError & vbNewLine)
            Exit Sub
        End If

        '==========================================================================='

        '==========================================================================='
        ' Create matcher
        '==========================================================================='
        m_Matcher = New UFMatcher()
        '==========================================================================='
    End Sub
    Sub CargaTanques()
        Dim cnConn As New SqlConnection
        Dim strSql As String
        Dim cmdBuscar As New SqlCommand
        Dim rdBuscar As SqlDataReader
        lstBomba.Items.Clear()

        Try
            cnConn.ConnectionString = CitraConnection
            strSql = "Select * from Tanques ORDER By Nombre"

            cmdBuscar.Connection = cnConn
            cmdBuscar.CommandText = strSql

            cnConn.Open()
            rdBuscar = cmdBuscar.ExecuteReader

            Do While rdBuscar.Read()
                lstBomba.Items.Add(rdBuscar("Nombre").ToString.Trim)
            Loop
        Catch ex As Exception
            MessageBox.Show(ex.Message, "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            If cnConn.State = ConnectionState.Open Then
                cnConn.Close()
            End If
        End Try
    End Sub
    Sub Actualizar()
        Dim intFolio As Integer = 0
        If Me.txtFolio.Text <> "" Then
            intFolio = Me.txtFolio.Text
            Diesel.IdDiesel = Me.txtFolio.Text
        Else
            intFolio = 0
            Diesel.IdDiesel = 0

        End If
        Diesel.Buscar()
        Scatter()
        Me.txtFolio.Text = intFolio
        Diesel.IdDiesel = Me.txtFolio.Text
    End Sub
    Private Sub Gatter()
        Dim FechaCarga As Date = datFecha.Value.ToString("MM/dd/yyyy")
        'ASIGNA VALORES PARA TABLA DIESEL
        Diesel.IdTanque = BuscarIntDatoCitra("SELECT IdTanque FROM Tanques WHERE Nombre='" & lstBomba.Text.Trim & "'")
        Diesel.NoCarga = BuscarIntDatoCitra("SELECT COUNT(*) FROM Diesel WHERE convert(varchar,fecha,101)='" & FechaCarga & "' AND IdTanque=" & Diesel.IdTanque)
        Diesel.Fecha = datFecha.Value
        Diesel.Hora = datFecha.Value
        Diesel.Cuentalitros = txtCuentalitros.Text
        Diesel.LitrosDisponibles = txtLitrosDisponibles.Text
        Diesel.Kardex = CDec(txtKardex.Text) - CDec(txtSurtidos.Text)
        Diesel.Precio = txtPrecio.Text
        Diesel.LitrosSurtidos = txtSurtidos.Text
        Diesel.IdAutobus = BuscarIntDatoCitra("SELECT IdAutobus FROM Autobuses WHERE NoEconomico='" & txtAutobus.Text.Trim & "'")
        Diesel.NoEconomico = txtAutobus.Text
        Diesel.IdRuta = BuscarIntDatoCitra("SELECT IdRuta FROM Rutas WHERE cCodigoV01='" & txtRuta.Text & "'")
        Diesel.NombreRuta = BuscarStrDatoCitra("SELECT Nombre FROM Rutas WHERE cCodigoV01='" & txtRuta.Text & "'")
        Diesel.Litros = txtLitros.Text
        Diesel.KilometrosTotales = txtKms.Text
        Diesel.KilometrosOperacion = txtOperacion.Text
        Diesel.KilometrosMuertos = txtMuertos.Text
        Diesel.RendimientoStandart = txtRendimientoStandar.Text
        Diesel.RendimientoAnterior = txtRendimientoAnterior.Text
        Diesel.RendimientoDia = txtRendimientoDia.Text
        Diesel.Subtotal = txtSubtotal.Text
        Diesel.IVA = txtIVA.Text
        Diesel.Total = txtTotal.Text
        Diesel.CodigoDespachador = BuscarStrDatoCitra("SELECT Codigo FROM Empleados WHERE IdEmpleado=" & IdEmpleado)
        Diesel.NombreDespachador = BuscarStrDatoCitra("SELECT NombreCompleto FROM Empleados WHERE IdEmpleado=" & IdEmpleado)
        'ASIGNA VALORES PARA TABLA DIESEL TEMPORAL
        Temp.IdTanque = Diesel.IdTanque
        Temp.NoCarga = Diesel.NoCarga
        Temp.Fecha = datFecha.Value
        Temp.IdAutobus = Diesel.IdAutobus
        Temp.NoEconomico = txtAutobus.Text
        Temp.IdRuta = Diesel.IdRuta
        Temp.NombreRuta = Diesel.NombreRuta
        Temp.Litros = txtLitros.Text
        Temp.KilometrosTotales = txtKms.Text
        Temp.KilometrosOperacion = txtOperacion.Text
        Temp.KilometrosMuertos = txtMuertos.Text
        Temp.Subtotal = txtSubtotal.Text
        Temp.IVA = txtIVA.Text
        Temp.Total = txtTotal.Text
        'ASIGNA VALORES PARA TABLA DIESEL SIN RECORRIDO

        If txtKms.Text = 0 Then
            DieselSinRecorrido.Fecha = datFecha.Value
            DieselSinRecorrido.IdAutobus = Diesel.IdAutobus
            DieselSinRecorrido.NoEconomico = txtAutobus.Text
            DieselSinRecorrido.Litros = txtLitros.Text
            DieselSinRecorrido.CodigoDespachador = Diesel.CodigoDespachador
            DieselSinRecorrido.NombreDespachador = Diesel.NombreDespachador
        End If
       

    End Sub
    Sub Verificar()
        Dim ufd_res As UFD_STATUS
        Dim ufm_res As UFM_STATUS
        ' Input finger data
        Dim Template As Byte() = New Byte(MAX_TEMPLATE_SIZE) {}
        Dim TemplateSize As Integer
        ' DB data
        Dim DBTemplate As Byte()() = Nothing
        Dim DBTemplateSize As Integer() = Nothing
        Dim DBSerial As Integer() = Nothing
        Dim DBTemplateNum As Integer
        '
        Dim MatchIndex As Integer

        ufd_res = m_Database.GetTemplateListWithSerial(DBTemplate, DBTemplateSize, DBTemplateNum, DBSerial)
        If (ufd_res <> UFD_STATUS.OK) Then
            UFDatabase.GetErrorString(ufd_res, m_strError)
            tbxMessage.AppendText("Obteniendo listado: " + m_strError + vbNewLine)
            Exit Sub
        End If

        If (Not ExtractTemplate(Template, TemplateSize)) Then
            Exit Sub
        End If

        DrawCapturedImage(m_Scanner)
        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        ufm_res = m_Matcher.Identify(Template, TemplateSize, DBTemplate, DBTemplateSize, DBTemplateNum, 5000, MatchIndex)
        Windows.Forms.Cursor.Current = Me.Cursor
        If (ufm_res <> UFM_STATUS.OK) Then
            UFMatcher.GetErrorString(ufm_res, m_strError)
            tbxMessage.AppendText("Identificación: " & m_strError & vbNewLine)
            Exit Sub
        End If

        If (MatchIndex <> -1) Then
            'tbxMessage.AppendText("Identification succeed (Serial = " & DBSerial(MatchIndex) & ")" & vbNewLine)
            Dim Codigo As String = BuscarStrDatoBiometriaOperadores("SELECT UserID FROM fingerprints WHERE Serial=" & DBSerial(MatchIndex))
            Dim Nombre As String = BuscarStrDatoCitra("SELECT Nombre FROM OperadoresGlobal WHERE Codigo='" & Codigo & "'")
            tbxMessage.AppendText("Operador identificado: " & Nombre & vbNewLine)
            Application.DoEvents()
            Diesel.CodigoOperador = Codigo
            Diesel.NombreOperador = Nombre
            DieselSinRecorrido.CodigoOperador = Diesel.CodigoOperador
            DieselSinRecorrido.NombreOperador = Diesel.NombreOperador
            Guardar()
            tbxMessage.AppendText("Guardado Éxitoso" & vbNewLine)
        Else
            tbxMessage.AppendText("No se encontro el operador" & vbNewLine)
        End If

    End Sub
    Private Function ExtractTemplate(ByRef Template As Byte(), ByRef TemplateSize As Integer) As Boolean
        Dim ufs_res As UFS_STATUS
        Dim EnrollQuality As Integer

        m_Scanner.ClearCaptureImageBuffer()

        tbxMessage.AppendText("Colocar dedo índice" & vbNewLine)

        TemplateSize = 0
        Do
            ufs_res = m_Scanner.CaptureSingleImage()
            If (ufs_res <> UFS_STATUS.OK) Then
                UFScanner.GetErrorString(ufs_res, m_strError)
                tbxMessage.AppendText("Capturando imágen: " & m_strError & vbNewLine)
                ExtractTemplate = False
                Exit Function
            End If

            DrawCapturedImage(m_Scanner)

            ufs_res = m_Scanner.Extract(Template, TemplateSize, EnrollQuality)
            If (ufs_res = UFS_STATUS.OK) Then
                tbxMessage.AppendText("Extracción de imagen: OK" & vbNewLine)
                Exit Do
            Else
                UFScanner.GetErrorString(ufs_res, m_strError)
                tbxMessage.AppendText("Extracción de imagen: " & m_strError & vbNewLine)
            End If
        Loop

        ExtractTemplate = True
    End Function
    Private Sub DrawCapturedImage(ByRef Scanner As UFScanner)
        Dim g As Graphics = pbImageFrame.CreateGraphics()
        Dim rect As Rectangle = New Rectangle(0, 0, pbImageFrame.Width, pbImageFrame.Height)
        Dim Resolution As Integer
        Try
            '
            'Scanner.DrawCaptureImageBuffer(g, rect, cbDetectCore.Checked);
            '
            Dim bitmap As Bitmap = Nothing
            Scanner.GetCaptureImageBuffer(bitmap, Resolution)
            pbImageFrame.Image = bitmap
        Finally
            g.Dispose()
        End Try
    End Sub

    Sub Guardar()
        'ACTUALIZA KILOMETRAJE DEL AUTOBUS
        Call SetSqlCitra("UPDATE Autobuses SET Importe01=Importe01+" & txtKms.Text & " WHERE NoEconomico='" & txtAutobus.Text & "'")
        'ACTUALIZA LITROS EXISTENTES EN TANQUE

        'ACTUALIZA CUENTALITROS DE DISPENSARIO
        Dim IdBomba As Integer = BuscarIntDatoCitra("SELECT IdBomba FROM Tanques WHERE Nombre='" & lstBomba.Text.Trim & "'")
        Call SetSqlCitra("UPDATE Bombas SET Numeracion_Actual=Numeracion_Actual+" & txtLitros.Text & " WHERE IdBomba=" & IdBomba)


        Gatter()
        Diesel.Insertar()
        Temp.Insertar()
        If txtKms.Text = 0 Then
            DieselSinRecorrido.Insertar()
        End If
        Imprimir()
        txtFolio.Text = BuscarIntDatoCitra("SELECT MAX(IdDiesel) AS ID FROM Diesel") + 1
        txtFolio.Text = 0
        BuscaDatosTanque()

    End Sub
    Sub Imprimir()

    End Sub
    Private Sub Scatter()
        Dim Fecha As String = datFecha.Value.ToString("MM/dd/yyyy")
        'lstBomba.SelectedText = BuscarStrDatoCitra("Tanques", "Nombre", "IdTanque=" & Diesel.IdTanque)
        'txtTotalCargas.Text = Diesel.NoCarga
        datFecha.Value = Diesel.Fecha
        'txtCuentalitros.Text = Format(Diesel.Cuentalitros, "###,###.#0")
        'txtLitrosDisponibles.Text = Format(Diesel.LitrosDisponibles, "###,###.#0")
        'txtKardex.Text = Format(Diesel.Kardex, "###,###.#0")
        'txtPrecio.Text = Format(Diesel.Precio, "###,###.#0")
        'txtSurtidos.Text = Format(Diesel.LitrosSurtidos, "###,###.#0")
        txtAutobus.Text = Diesel.NoEconomico
        txtRuta.Text = Diesel.NombreRuta
        txtRendimientoStandar.Text = Format(Diesel.RendimientoStandart, "###,###.#0")
        txtRendimientoAnterior.Text = Format(Diesel.RendimientoAnterior, "###,###.#0")
        txtLitros.Text = Format(Diesel.Litros, "###,###.#0")
        'txtKms.Text = Format(Diesel.Kilometros, "###,###.#0")
        txtRendimientoDia.Text = Format(Diesel.RendimientoDia, "###,###.#0")
        txtSubtotal.Text = Format(Diesel.Subtotal, "###,###.#0")
        txtIVA.Text = Format(Diesel.IVA, "###,###.#0")
        txtTotal.Text = Format(Diesel.Total, "###,###.#0")
    End Sub

    Private Sub txtFolio_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtFolio.TextChanged
        Actualizar()
    End Sub
    Sub CargaBuses()
        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        dgBuses.Rows.Clear()

        Dim strNombre As String
        Dim cnconn As New SqlConnection
        Dim strSql As String
        Dim cmdBuscar As New SqlCommand
        Dim rdBuscar As SqlDataReader

        Try
            strNombre = UCase(txtBuscarBus.Text.Trim)
            strNombre = "%" & strNombre.Replace(" ", "%") & "%"

            cnconn.ConnectionString = CitraConnection
            strSql = "Select IdAutobus, cCodigoC01, NoEconomico FROM Autobuses WHERE (Estatus=1 and upper(cCodigoC01) Like '" & strNombre & "' " & mstrCondicion & ") OR  (Estatus=1 and upper(NoEconomico) like '" & strNombre & "' " & mstrCondicion & ")"

            cmdBuscar.Connection = cnconn
            cmdBuscar.CommandText = strSql

            cnconn.Open()
            rdBuscar = cmdBuscar.ExecuteReader

            Do While rdBuscar.Read()
                dgBuses.Rows.Add(rdBuscar("cCodigoC01").ToString.Trim, rdBuscar("NoEconomico").ToString.Trim, rdBuscar("IdAutobus"))
            Loop
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Aviso")
        Finally
            If cnconn.State = ConnectionState.Open Then
                cnconn.Close()
            End If
        End Try

    End Sub
    Sub CargaRutas()
        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        dgRuta.Rows.Clear()

        Dim strNombre As String
        Dim cnconn As New SqlConnection
        Dim strSql As String
        Dim cmdBuscar As New SqlCommand
        Dim rdBuscar As SqlDataReader

        Try
            strNombre = UCase(txtBuscarRuta.Text.Trim)
            strNombre = "%" & strNombre.Replace(" ", "%") & "%"

            cnconn.ConnectionString = CitraConnection
            strSql = "Select * FROM RUTAS WHERE upper(cCodigoV01) Like '" & strNombre & "' " & mstrCondicion & " OR  upper(Nombre) like '" & strNombre & "' " & mstrCondicion & ""

            cmdBuscar.Connection = cnconn
            cmdBuscar.CommandText = strSql

            cnconn.Open()
            rdBuscar = cmdBuscar.ExecuteReader

            Do While rdBuscar.Read()
                dgRuta.Rows.Add(rdBuscar("cCodigoV01").ToString.Trim, rdBuscar("Nombre").ToString.Trim)
            Loop
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Aviso")
        Finally
            If cnconn.State = ConnectionState.Open Then
                cnconn.Close()
            End If
        End Try

    End Sub

    Private Sub txtAutobus_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtAutobus.KeyPress
        If e.KeyChar = Chr(Keys.Enter) Then
            Dim Id As Integer = BuscarIntDatoCitra("Autobuses", "IdAutobus", "NoEconomico='" & txtAutobus.Text.Trim & "' and estatus=1")
            If Id > 0 Then
                txtRuta.Text = BuscarStrDatoCitra("Select Rutas.cCodigoV01 FROM Rutas INNER JOIN Autobuses ON Rutas.IdRuta=Autobuses.IdRuta WHERE Autobuses.IdAutobus=" & Id)
                BuscarRendimiento()
                BuscarKilometros()
                txtLitros.Focus()
            Else
                MsgBox("El autobus no existe o se encuentra inactivo", MsgBoxStyle.Exclamation, "Aviso")
                txtAutobus.SelectAll()
            End If

        End If
    End Sub

    Private Sub txtAutobus_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtAutobus.TextChanged

    End Sub
    Sub BuscarKilometros()
        Dim Cod_Vehiculo As String = BuscarStrDatoCitra("SELECT Cod_Vehiculo FROM Autobuses WHERE NoEconomico='" & txtAutobus.Text.Trim & "'")
        Dim KilometrosTotales As Double
        Dim KilometrosOperacion As Double
        Dim KilometrosMuertos
        If Cod_Vehiculo = "" Then 'KILOMETROS CALCULADOS POR ODOMETRO
            txtKms.Text = Format(0, "###,###.#0")
            txtOperacion.Text = Format(0, "###,###.#0")
            txtMuertos.Text = Format(0, "###,###.#0")
            Dim strResult As String
            Dim fBusqueda As New frmOometroActual
            Dim OdometroActual As Double
            Dim OdometroInicial As Double

            fBusqueda.ShowDialog()

            If fBusqueda.DialogResult = Windows.Forms.DialogResult.OK Then
                strResult = fBusqueda.Valor
                If strResult > 0 Then
                    OdometroActual = strResult
                    OdometroInicial = BuscarDblDatoCitra("SELECT Importe01 FROM Autobuses WHERE NoEconomico='" & txtAutobus.Text.Trim & "'")
                    KilometrosTotales = OdometroActual - OdometroInicial
                    If KilometrosTotales < 1 Then
                        MsgBox("La numeracion del odometro es incorrecta", MsgBoxStyle.Exclamation, "Aviso")
                        Exit Sub
                    End If
                    Dim IdAutobus As Integer = BuscarIntDatoCitra("SELECT IdAutobus FROM Autobuses WHERE NoEconomico='" & txtAutobus.Text.Trim & "'")
                    Dim Vueltas As Double = BuscarDblDatoCitra("SELECT Vueltas FROM Liquidacion Where IdAutobus=" & IdAutobus & " ORDER BY IdLiquidacion DESC")
                    Dim IdRuta As Integer = BuscarIntDatoCitra("SELECT IdRuta FROM Liquidacion Where IdAutobus=" & IdAutobus & " ORDER BY IdLiquidacion DESC")
                    Dim KilometrosRuta As Double = BuscarDblDatoCitra("SELECT Kilometros FROM Rutas Where IdRuta=" & IdRuta)
                    KilometrosOperacion = Vueltas * KilometrosRuta
                    KilometrosMuertos = KilometrosTotales - KilometrosOperacion

                    txtKms.Text = Format(KilometrosTotales, "###,###.#0")
                    txtOperacion.Text = Format(KilometrosOperacion, "###,###.#0")
                    txtMuertos.Text = Format(KilometrosMuertos, "###,###.#0")
                End If
            Else
                MsgBox("Debes indicar el odometro actual", MsgBoxStyle.Exclamation, "Aviso")
                Exit Sub
            End If
           
        Else 'KILOMETROS CALCULADOS POR OPTOCONTROL

            'Buscar Kilometros Totales
            Dim IdHorario As Integer = BuscarIntDatoCitra("SELECT MAX(IdHorario) as Id FROM HorariosDiesel D INNER JOIN Autobuses A ON D.IdAutobus=A.IdAutobus WHERE NoEconomico='" & txtAutobus.Text.Trim.Trim & "'")
            Dim UltimaCarga
            Dim FechaFormateada As String
            Dim FechaInicial As String
            Dim ID_VEHICULO As Guid
           
            Dim strID_VEHICULO As String

            If IdHorario > 0 Then 'SI HAY REGISTROS DE HORARIO
                UltimaCarga = BuscarDateDatoCitra("SELECT MAX(ULTIMA_FECHA_HORA) AS FechaHora FROM HorariosDiesel D INNER JOIN Autobuses A ON D.IdAutobus=A.IdAutobus WHERE NoEconomico='" & txtAutobus.Text.Trim.Trim & "'")
                FechaFormateada = Format(CDate(UltimaCarga), "MM/dd/yyyy hh:mm:sszzz")
                FechaInicial = Format(CDate(UltimaCarga), "MM/dd/yyyy")
                'ID_VEHICULO = BuscarGuidDatoOptoControl("SELECT ID_VEHICULO FROM VEHICULO WHERE COD_VEHICULO='" & Cod_Vehiculo & "'")
                strID_VEHICULO = ID_VEHICULO.ToString
                KilometrosTotales = BuscarDblDatoOptoControl("SELECT SUM(DISTANCIA) AS KMS FROM REGISTRO WHERE ID_VEHICULO='" & strID_VEHICULO & "' AND CONVERT(VARCHAR,FECHA_HORA,9)>'" & FechaFormateada & "'")
                KilometrosOperacion = BuscarDblDatoCitra("SELECT SUM(KILOMETROS) AS KMS FROM KilometrosOperativos WHERE Vehiculo='" & Cod_Vehiculo & "' AND CONVERT(VARCHAR,FECHA,101)>'" & FechaInicial & "'") 'BuscarDblDatoOptoControl("SELECT SUM(KILOMETROS) AS KMS FROM HISTORICO_RECAUDACION WHERE ID_VEHICULO='" & strID_VEHICULO & "' AND CONVERT(VARCHAR,FECHA_HORA_FIN,9)>'" & FechaFormateada & "'")
                KilometrosMuertos = KilometrosTotales - KilometrosOperacion

            Else 'NO HAY REGISTROS DE HORARIO
                UltimaCarga = datFecha.Value
                FechaFormateada = Format(CDate(UltimaCarga), "MM/dd/yyyy")
                'ID_VEHICULO = BuscarGuidDatoOptoControl("SELECT ID_VEHICULO FROM VEHICULO WHERE COD_VEHICULO='" & Cod_Vehiculo & "'")
                strID_VEHICULO = ID_VEHICULO.ToString
                KilometrosTotales = BuscarDblDatoOptoControl("SELECT SUM(DISTANCIA) AS KMS FROM REGISTRO WHERE ID_VEHICULO='" & strID_VEHICULO & "' AND CONVERT(VARCHAR,FECHA,101)>='" & FechaFormateada & "'")
                KilometrosOperacion = BuscarDblDatoCitra("SELECT SUM(KILOMETROS) AS KMS FROM KilometrosOperativos WHERE Vehiculo='" & Cod_Vehiculo & "' AND CONVERT(VARCHAR,FECHA,101)>='" & FechaFormateada & "'") 'BuscarDblDatoOptoControl("SELECT SUM(KILOMETROS) AS KMS FROM HISTORICO_RECAUDACION WHERE ID_VEHICULO='" & strID_VEHICULO & "' AND CONVERT(VARCHAR,FECHA_HORA_FIN,9)>'" & FechaFormateada & "'")
                KilometrosMuertos = KilometrosTotales - KilometrosOperacion
            End If
            txtKms.Text = Format(KilometrosTotales, "###,###.#0")
            txtOperacion.Text = Format(KilometrosOperacion, "###,###.#0")
            txtMuertos.Text = Format(KilometrosMuertos, "###,###.#0")



        End If
    End Sub
    Private Sub NuevaToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NuevaToolStripMenuItem.Click
        txtFolio.Text = (BuscarIntDatoCitra("Select MAX(IdDiesel) as Id from Diesel")) + 1
        txtFolio.Text = 0
        txtAutobus.Focus()

        BuscaDatosTanque()
    End Sub

    Private Sub txtRuta_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtRuta.KeyPress
        If e.KeyChar = Chr(Keys.Enter) Then
            Dim Codigo As String = BuscarStrDatoCitra("SELECT CCodigoV01 FROM RUTAS WHERE CCodigoV01='" & txtRuta.Text.Trim & "'")

            If Codigo.Trim <> "" Then
                txtLitros.Focus()
            Else
                MsgBox("La ruta indicada no existe", MsgBoxStyle.Exclamation, "Aviso")
                txtRuta.Focus()
                txtRuta.SelectAll()
            End If

        End If
    End Sub

    Private Sub txtRuta_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtRuta.TextChanged

    End Sub

    Private Sub btnBuscarAutobus_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBuscarAutobus.Click
        panelRutas.Visible = False
        'panelNombres.Visible = False

        panelBuses.Visible = True
        txtBuscarBus.Focus()
        txtBuscarBus.Clear()
        txtBuscarBus.SelectAll()
    End Sub

    Private Sub btnBuscarRuta_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBuscarRuta.Click
        panelBuses.Visible = False
        'panelNombres.Visible = False

        panelRutas.Visible = True
        txtBuscarRuta.Focus()
        txtBuscarRuta.Clear()
        txtBuscarRuta.SelectAll()
    End Sub

    Private Sub lstBomba_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstBomba.SelectedIndexChanged
        DatosAdminpaq()
        BuscaDatosTanque()
    End Sub
    Sub BuscaDatosTanque()
        Dim cnConn As New SqlConnection
        Dim strSql As String
        Dim cmdBuscar As New SqlCommand
        Dim rdBuscar As SqlDataReader

        Dim Altura As Double
        Dim Longitud As Double
        Dim Diametro As Double
        Dim Radio As Double
        Dim AlfaRadianes As Double
        Dim AlfaGrados As Double
        Dim Volumen As Double
        Dim Heliptica As Double
        Dim VolumenH As Double
        Dim VolumenTotal As Double
        Dim Existencia As Double
        Dim NumeracionActual As Double
        Dim IdTanque As Integer


        Try
            cnConn.ConnectionString = CitraConnection
            strSql = "SELECT IdTanque,T.IdAlmacen,Longitud, Diametro, AltoGlobo,Capacidad,Medida_Actual,Numeracion_Actual FROM Tanques T INNER JOIN Bombas B ON T.IdBomba=B.IdBomba WHERE T.Nombre='" & lstBomba.Text & "'"

            cmdBuscar.Connection = cnConn
            cmdBuscar.CommandText = strSql

            cnConn.Open()
            rdBuscar = cmdBuscar.ExecuteReader



            If rdBuscar.Read() Then
                Altura = rdBuscar("Medida_Actual")
                Longitud = rdBuscar("Longitud")
                Diametro = rdBuscar("Diametro")
                Radio = Diametro / 2
                AlfaRadianes = Math.Acos(1 - (Altura / Radio))
                AlfaGrados = (AlfaRadianes * 180) / 3.1416
                Volumen = Longitud * (Radio * Radio) * (AlfaGrados / 57.3 - (Math.Sin(AlfaRadianes) * Math.Cos(AlfaRadianes)))
                Heliptica = rdBuscar("AltoGlobo")
                If Heliptica > 0 Then
                    VolumenH = 3.1416 * (Diametro * Diametro) * Heliptica / 6
                    VolumenTotal = VolumenH * 2 + Volumen
                    Existencia = VolumenTotal * 1000
                Else
                    VolumenTotal = Volumen
                    Existencia = VolumenTotal * 1000
                End If
                NumeracionActual = rdBuscar("Numeracion_Actual")
                IdTanque = rdBuscar("IdTanque")
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            If cnConn.State = ConnectionState.Open Then
                cnConn.Close()
            End If
        End Try

        Dim Litros As Double = BuscarDblDatoCitra("SELECT SUM(Litros) as Litros FROM DieselTemp")
        txtCuentalitros.Text = Format(NumeracionActual, "###,###.#0")
        txtLitrosDisponibles.Text = Format(Existencia - Litros, "###,###.#0")
        txtSurtidos.Text = Format(Litros, "###,###.#0")
        lblDiferencia.Text = Format(Existencia - CDbl(txtKardex.Text), "###,###.#0")
    End Sub
    Sub DatosAdminpaq()
        Dim cIdAlmacen As Integer = BuscarIntDatoCitra("Tanques", "IdAlmacen", "Nombre='" & lstBomba.Text & "'")

        Dim Ejercicio As Integer = BuscarIntDatoCitra("SELECT MAX(cIdEjerc01) as Id FROM MGW10031")
        Dim Entradas As Double = BuscarDblDatoCitra("SELECT cEntrada12 FROM MGW10030 WHERE cIdProdu01=" & cIdProdu01 & " AND cIdEjerc01=" & Ejercicio & " AND cIdAlmacen=" & cIdAlmacen)
        Dim Salidas As Double = BuscarDblDatoCitra("SELECT cSalidas01 FROM MGW10030 WHERE cIdProdu01=" & cIdProdu01 & " AND cIdEjerc01=" & Ejercicio & " AND cIdAlmacen=" & cIdAlmacen)
        Dim Kardex As Double = Entradas - Salidas
        txtKardex.Text = Format(Kardex, "###,###.#0")
        Dim Costo As Double = BuscarDblDatoCitra("SELECT MAX(cUltimoC01) AS Costo FROM MGW10017 WHERE cIdProdu01=" & cIdProdu01 & " AND cIdAlmacen=" & cIdAlmacen)
        txtPrecio.Text = Format(Costo, "###,###.#000")

    End Sub

    Private Sub txtBuscarBus_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtBuscarBus.KeyPress
        If e.KeyChar = Chr(Keys.Enter) Then
            panelBuses.Visible = False
            Dim Nombre As String = dgBuses.CurrentRow.Cells(1).Value.ToString.Trim
            txtAutobus.Text = Nombre
            txtRuta.Text = BuscarStrDatoCitra("Select Rutas.cCodigoV01 FROM Rutas INNER JOIN Autobuses ON Rutas.IdRuta=Autobuses.IdRuta WHERE Autobuses.NoEconomico='" & Nombre & "'")
            txtLitros.Focus()
            txtLitros.SelectAll()
        ElseIf e.KeyChar = Chr(Keys.Escape) Then
            panelBuses.Visible = False
        End If
    End Sub

    Private Sub txtBuscarBus_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtBuscarBus.TextChanged
        CargaBuses()

    End Sub

    Private Sub txtBuscarRuta_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtBuscarRuta.KeyPress
        If e.KeyChar = Chr(Keys.Enter) Then
            panelRutas.Visible = False
            Dim Nombre As String = dgRuta.CurrentRow.Cells(0).Value.ToString.Trim
            txtRuta.Text = Nombre
            txtLitros.Focus()
            txtLitros.SelectAll()
        ElseIf e.KeyChar = Chr(Keys.Escape) Then
            panelRutas.Visible = False
        End If
    End Sub

    Private Sub txtBuscarRuta_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtBuscarRuta.TextChanged
        CargaRutas()

    End Sub
    Private Sub dgBuses_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgBuses.CellDoubleClick
        panelBuses.Visible = False
        Dim Nombre As String = dgBuses.CurrentRow.Cells(1).Value.ToString.Trim
        txtAutobus.Text = Nombre
        txtRuta.Text = BuscarStrDatoCitra("Select Rutas.cCodigoV01 FROM Rutas INNER JOIN Autobuses ON Rutas.IdRuta=Autobuses.IdRuta WHERE Autobuses.NoEconomico='" & Nombre & "'")
        txtLitros.Focus()
        txtLitros.SelectAll()
    End Sub
    Private Sub dgRuta_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgRuta.CellDoubleClick
        panelRutas.Visible = False
        Dim Nombre As String = dgRuta.CurrentRow.Cells(0).Value.ToString.Trim
        txtRuta.Text = Nombre
        txtLitros.Focus()
        txtLitros.SelectAll()
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If LeerEstatus(1) = 0 Then
            txtLitros.Text = VentaLitros(1).ToString '"-999999" '
        Else
            MsgBox("Dispensario Ocupado", MsgBoxStyle.Information, "Aviso")
        End If
    End Sub



    Private Sub txtLitros_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtLitros.TextChanged
        If txtLitros.Text = "" Then
            txtLitros.Text = 0
        End If
    End Sub

    Private Sub ConfigurarPuertoToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConfigurarPuertoToolStripMenuItem.Click
        frmConectaSerial.ShowDialog()

    End Sub

    Private Sub RegistrarHuellaOperadoresToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RegistrarHuellaOperadoresToolStripMenuItem.Click
        frmAltaHuellasOperadores.ShowDialog()
    End Sub

    Private Sub ToolStripButton5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton5.Click
        If txtAutobus.Text = "" Then
            MsgBox("Debes indicar un autobus", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If

        If txtRuta.Text = "" Then
            MsgBox("Debes indicar la ruta", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If

        If txtLitros.Text = 0 Then
            MsgBox("No se puede guardar un registro sin litros", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If

        Verificar()

    End Sub

    Private Sub CerrarDiaToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CerrarDiaToolStripMenuItem.Click

    End Sub

    Private Sub ReAbrirDiaToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReAbrirDiaToolStripMenuItem.Click

    End Sub
End Class